<?php


namespace app\shop\controller;

use app\model\express\ExpressTemplate as ExpressTemplateModel;
use app\model\goods\Goods as GoodsModel;
use app\model\goods\GoodsLabel as GoodsLabelModel;
use app\model\goods\GoodsService as GoodsServiceModel;
use app\model\message\Message;
use app\model\order\Config as ConfigModel;
use app\model\order\OrderCommon as OrderCommonModel;
use app\model\order\Order as OrderModel;
use app\model\order\OrderCommon;
use app\model\order\OrderExport;
use think\facade\Config;
use app\model\system\Promotion as PromotionModel;
use phpoffice\phpexcel\Classes\PHPExcel;
use phpoffice\phpexcel\Classes\PHPExcel\Writer\Excel2007;
use think\facade\Db;

/**
 * 订单
 * Class Order
 * @package app\shop\controller
 */
class Order extends BaseShop
{

    public function __construct()
    {
        //执行父类构造函数
        parent::__construct();

    }

    /**
     * 快递订单列表
     */
    public function lists()
    {
        $order_label_list = array(
            "order_no" => "订单号",
            "out_trade_no" => "外部单号",
            "name" => "收货人姓名",
            "order_name" => "商品名称",
        );
        $order_status = input("order_status", "");//订单状态
        $order_name = input("order_name", '');
        $pay_type = input("pay_type", '');
        $order_from = input("order_from", '');
        $start_time = input("start_time", '');
        $end_time = input("end_time", '');
        $order_label = !empty($order_label_list[input("order_label")]) ? input("order_label") : "";
        $search_text = input("search", '');
        $order_type = input("order_type", 'all');//营销类型
        $check = input("check", '');
        $project_name = input("project_name", '');
        $order_common_model = new OrderCommonModel();
        if (request()->isAjax()) {
            $page_index = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);
            $condition = [
//                ["order_type", "=", 1],
                ["site_id", "=", $this->site_id],
                ['is_delete', '=', 0]
            ];

            //2020-10-29审批状态搜索
            if (!empty($check)) {
                $check_status = ($check == 1) ? 0 : (($check == 2) ? 1 : 2);
                $condition[] = ["check", "=", $check_status];
            }

            //项目名称
            if ($project_name != "") {
                $condition[] = ["project_name", "like", "%$project_name%"];
            }
            //订单状态
            if ($order_status != "") {
                $condition[] = ["order_status", "=", $order_status];
            }
            //订单内容 模糊查询
            if ($order_name != "") {
                $condition[] = ["order_name", 'like', "%$order_name%"];
            }
            //订单来源
            if ($order_from != "") {
                $condition[] = ["order_from", "=", $order_from];
            }
            //订单支付
            if ($pay_type != "") {
                $condition[] = ["pay_type", "=", $pay_type];
            }
            //订单类型
            if ($order_type != 'all') {
                $condition[] = ["order_type", "=", $order_type];
            }

            if (!empty($start_time) && empty($end_time)) {
                $condition[] = ["create_time", ">=", date_to_time($start_time)];
            } elseif (empty($start_time) && !empty($end_time)) {
                $condition[] = ["create_time", "<=", date_to_time($end_time)];
            } elseif (!empty($start_time) && !empty($end_time)) {
                $condition[] = ['create_time', 'between', [date_to_time($start_time), date_to_time($end_time)]];
            }

            if ($search_text != "") {
                $condition[] = [$order_label, 'like', "%$search_text%"];
            }

            $list = $order_common_model->getOrderPageList($condition, $page_index, $page_size, "create_time desc");
            return $list;
        } else {

            $order_type_list = $order_common_model->getOrderTypeStatusList();
            $this->assign("order_type_list", $order_type_list);
            $this->assign("order_label_list", $order_label_list);
            $order_model = new OrderModel();
            $order_status_list = $order_model->order_status;
            $this->assign("order_status_list", $order_status_list);//订单状态

            //订单来源 (支持端口)
            $order_from = Config::get("app_type");
            $this->assign('order_from_list', $order_from);

            $pay_type = $order_common_model->getPayType();
            $this->assign("pay_type_list", $pay_type);

            //营销活动类型
            $order_promotion_type = event('OrderPromotionType');
            $this->assign("promotion_type", $order_promotion_type);
            $this->assign("http_type", get_http_type());

            return $this->fetch('order/lists');
        }

    }

    /**
     * 供应商订单列表
     */
    public function offer_lists()
    {
        $order_label_list = array(
            "order_no" => "订单号",
            "out_trade_no" => "外部单号",
            "name" => "收货人姓名",
            "order_name" => "商品名称",
        );
        $order_status = input("order_status", "");//订单状态
        $order_name = input("order_name", '');
        $order_from = input("order_from", '');
        $start_time = input("start_time", '');
        $end_time = input("end_time", '');
        $order_label = !empty($order_label_list[input("order_label")]) ? input("order_label") : "";
        $search_text = input("search", '');
        $promotion_type = input("promotion_type", '');//订单类型
        $order_type = input("order_type", 'all');//营销类型
        $project_name = input("project_name", '');
        $order_common_model = new OrderCommonModel();
        if (request()->isAjax()) {
            $page_index = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);
            $condition = [
                //只能查找已审批，未删除，后台管理员已审核，且供应商为自己的订单
                ["check", "=", 1],
                ["offer_member", "=", $this->uid],
                ["site_id", "=", 1],
                ['is_delete', '=', 0],
                ['review', '=', 1],
            ];

            //项目名称
            if ($project_name != "") {
                $condition[] = ["project_name", "like", "%$project_name%"];
            }

            //订单状态
            if ($order_status != "") {
                $condition[] = ["order_status", "=", $order_status];
            }

            //订单内容 模糊查询
            if ($order_name != "") {
                $condition[] = ["order_name", 'like', "%$order_name%"];
            }
            //订单来源
            if ($order_from != "") {
                $condition[] = ["order_from", "=", $order_from];
            }
            //订单类型
            if ($order_type != 'all') {
                $condition[] = ["order_type", "=", $order_type];
            }
            //营销类型
            if ($promotion_type != "") {
                if ($promotion_type == 'empty') {
                    $condition[] = ["promotion_type", "=", ''];
                } else {
                    $condition[] = ["promotion_type", "=", $promotion_type];
                }
            }
            if (!empty($start_time) && empty($end_time)) {
                $condition[] = ["create_time", ">=", date_to_time($start_time)];
            } elseif (empty($start_time) && !empty($end_time)) {
                $condition[] = ["create_time", "<=", date_to_time($end_time)];
            } elseif (!empty($start_time) && !empty($end_time)) {
                $condition[] = ['create_time', 'between', [date_to_time($start_time), date_to_time($end_time)]];
            }
            if ($search_text != "") {
                $condition[] = [$order_label, 'like', "%$search_text%"];
            }

            $list = $order_common_model->getOfferOrderPageList($condition, $page_index, $page_size, "create_time desc");
            return $list;
        } else {

            $order_type_list = $order_common_model->getOrderTypeStatusList();
            $this->assign("order_type_list", $order_type_list);
            $this->assign("order_label_list", $order_label_list);
            $order_model = new OrderModel();
            $order_status_list = $order_model->order_status;
            $this->assign("order_status_list", $order_status_list);//订单状态

            //订单来源 (支持端口)
            $order_from = Config::get("app_type");
            $this->assign('order_from_list', $order_from);

            $pay_type = $order_common_model->getPayType();
            $this->assign("pay_type_list", $pay_type);

            //营销活动类型
            $order_promotion_type = event('OrderPromotionType');
            $this->assign("promotion_type", $order_promotion_type);
            $this->assign("http_type", get_http_type());

            return $this->fetch('order/offer_lists');
        }

    }

    /**
     * 快递订单详情
     */
    public function detail()
    {
        $order_id = input("order_id", 0);
        $order_common_model = new OrderCommonModel();
        if ($this->user_info['group_id'] == 5){
            $order_detail_result = $order_common_model->getOfferOrderDetail($order_id, $this->uid);
        }else{
            $order_detail_result = $order_common_model->getOrderDetail($order_id);
        }
        $order_detail = $order_detail_result["data"];
        $this->assign("order_detail", $order_detail);
        switch ($order_detail["order_type"]) {
            case 1 :
                $template = "order/detail";
                break;
            case 2 :
                $template = "storeorder/detail";
                break;
            case 3 :
                $template = "localorder/detail";
                break;
            case 4 :
                $template = "virtualorder/detail";
                break;
        }

        $this->assign("http_type", get_http_type());
        return $this->fetch($template);
    }

    /**
     * 订单设置
     */
    public function config()
    {
        $config_model = new ConfigModel();
        if (request()->isAjax()) {
            //订单事件时间设置数据
            $order_event_time_config_data = [
                'auto_close' => input('order_auto_close_time', 0),//订单未付款自动关闭时间 数字 单位(天)
                'auto_take_delivery' => input('order_auto_take_delivery_time', 0),//订单发货后自动收货时间 数字 单位(天)
                'auto_complete' => input('order_auto_complete_time', 0),//订单收货后自动完成时间 数字 单位(天)

                'invoice_status' => input('invoice_status', 0),
                'invoice_rate' => input('invoice_rate', 0),
                'invoice_content' => input('invoice_content', ''),
                'invoice_money' => input('invoice_money', 0),
            ];
            $res = $config_model->setOrderEventTimeConfig($order_event_time_config_data, $this->site_id, $this->app_module);
            return $res;
        } else {

            //订单事件时间设置
            $order_event_time_config = $config_model->getOrderEventTimeConfig($this->site_id, $this->app_module);
            $this->assign('order_event_time_config', $order_event_time_config['data']['value']);
            return $this->fetch('order/config');
        }
    }

    /**
     * 订单关闭
     * @return mixed
     */
    public function close()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $order_common_model = new OrderCommonModel();
            $result = $order_common_model->orderClose($order_id);
            return $result;
        }
    }

    /**
     * 推送到审批员
     * @return mixed
     */
    public function push()
    {
        if (request()->isAjax()) {
            $order_id           = input("order_id", 0);
            $order_common_model = new OrderCommonModel();
            $result             = $order_common_model->orderPush($order_id);
            return $result;
        }
    }

    /**
     * 订单调价
     * @return mixed
     */
    public function adjustPrice()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $adjust_money = input("adjust_money", 0);
            $delivery_money = input("delivery_money", 0);
            $order_common_model = new OrderCommonModel();
            $result = $order_common_model->orderAdjustMoney($order_id, $adjust_money, $delivery_money);
            return $result;
        }
    }

    /**
     * 订单发货
     * @return mixed
     */
    public function delivery()
    {
        if (request()->isAjax()) {

            $order_model = new OrderModel();
            $data = array(
                "type" => input('type', 'manual'),//发货方式（手动发货、电子面单）
                "order_goods_ids" => input("order_goods_ids", ''),//商品id
                "express_company_id" => input("express_company_id", 0),//物流公司
                "delivery_no" => input("delivery_no", ''),//快递单号
                "order_id" => input("order_id", 0),//订单id
                "delivery_type" => input("delivery_type", 0),//是否需要物流
                "site_id" => $this->site_id,
                "template_id" => input('template_id', 0)//电子面单模板id
            );

            $result = $order_model->orderGoodsDelivery($data, 1, $this->uid);
            return $result;
        } else {
            $order_id = input("order_id", 0);
            $delivery_status = input("delivery_status", '');
            $order_common_model = new OrderCommonModel();
            $condition = array(
                ["order_id", "=", $order_id],
                ["site_id", "=", $this->site_id],
                //2020-11-10新增 供应商只能查看自己的那部分商品
                ["offer_member", "=", $this->uid],
            );
            if ($delivery_status === '') {
                $condition[] = ["delivery_status", "=", $delivery_status];
            }
            $field = "order_goods_id, order_id, site_id, site_name, sku_name, sku_image, sku_no, is_virtual, price, cost_price, num, goods_money, cost_money, delivery_status, delivery_no, goods_id, delivery_status_name";
            $order_goods_list_result = $order_common_model->getOrderGoodsList($condition, $field, '', null, "delivery_no");
            $order_goods_list = $order_goods_list_result["data"];
            $this->assign("order_goods_list", $order_goods_list);
            return $this->fetch("order/delivery");
        }
    }

    /**
     * 获取订单项列表
     */
    public function getOrderGoodsList()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $delivery_status = input("delivery_status", '');
            $order_common_model = new OrderCommonModel();
            $condition = array(
                ["order_id", "=", $order_id],
                ["site_id", "=", $this->site_id],
                ["refund_status", "<>", 3],
                //2020-11-10新增 供应商只能查看自己的那部分商品
                ["offer_member", "=", $this->uid],
            );
            if ($delivery_status != '') {
                $condition[] = ["delivery_status", "=", $delivery_status];
            }
            $field = "order_goods_id, order_id, site_id, sku_name, sku_image, sku_no, is_virtual, price, cost_price, num, goods_money, cost_money, delivery_status, delivery_no, goods_id, delivery_status_name";
            $result = $order_common_model->getOrderGoodsList($condition, $field, '', null, "");
            return $result;
        }
    }

    /**
     * 订单修改收货地址
     * @return mixed
     */
    public function editAddress()
    {
        $order_id = input("order_id", 0);
        if (request()->isAjax()) {
            $order_model = new OrderModel();
            $province_id = input("province_id");
            $city_id = input("city_id");
            $district_id = input("district_id");
            $community_id = input("community_id");
            $address = input("address");
            $full_address = input("full_address");
            $longitude = input("longitude");
            $latitude = input("latitude");
            $mobile = input("mobile");
            $telephone = input("telephone");
            $name = input("name");
            $data = array(
                "province_id" => $province_id,
                "city_id" => $city_id,
                "district_id" => $district_id,
                "community_id" => $community_id,
                "address" => $address,
                "full_address" => $full_address,
                "longitude" => $longitude,
                "latitude" => $latitude,
                "mobile" => $mobile,
                "telephone" => $telephone,
                "name" => $name,
            );
            $condition = array(
                ["order_id", "=", $order_id],
                ["site_id", "=", $this->site_id]
            );
            $result = $order_model->orderAddressUpdate($data, $condition);
            return $result;
        }
    }

    /**
     * 获取订单信息
     */
    public function getOrderInfo()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $order_common_model = new OrderCommonModel();
            $condition = array(
                ["order_id", "=", $order_id],
                ["site_id", "=", $this->site_id],
            );
            $result = $order_common_model->getOrderInfo($condition);
            return $result;
        }
    }

    /**
     * 获取订单 订单项内容
     */
    public function getOrderDetail()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $order_common_model = new OrderCommonModel();
            $result = $order_common_model->getOrderDetail($order_id);
            return $result;
        }
    }

    /**
     * 卖家备注
     */
    public function orderRemark()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $remark = input("remark", 0);
            $order_common_model = new OrderCommonModel();
            $condition = array(
                ["order_id", "=", $order_id],
                ["site_id", "=", $this->site_id],
            );
            $data = array(
                "remark" => $remark
            );
            $result = $order_common_model->orderUpdate($data, $condition);
            return $result;
        }
    }

    /**
     * 订单导出（已订单为主）
     */
    public function exportOrder()
    {
        $order_status = input("order_status", "");//订单状态
        $order_name = input("order_name", '');
        $pay_type = input("pay_type", '');
        $order_from = input("order_from", '');
        $start_time = input("start_time", '');
        $end_time = input("end_time", '');
        $order_label = input("order_label",'');
        $search_text = input("search", '');
        $promotion_type = input("promotion_type", '');
        $order_type = input("order_type", 'all');

        $condition[] = ["site_id", "=", $this->site_id];

        if($order_type != 'all'){
            $condition[] = ["order_type", "=", $order_type];
        }

        //订单状态
        if ($order_status != "") {
            $condition[] = ["order_status", "=", $order_status];
        }
        //订单内容 模糊查询
        if ($order_name != "") {
            $condition[] = ["order_name", 'like', "%$order_name%"];
        }
        //订单来源
        if ($order_from != "") {
            $condition[] = ["order_from", "=", $order_from];
        }
        //订单支付
        if ($pay_type != "") {
            $condition[] = ["pay_type", "=", $pay_type];
        }
        //营销类型
        if ($promotion_type != "") {
            if ($promotion_type == 'empty') {
                $condition[] = ["promotion_type", "=", ''];
            } else {
                $condition[] = ["promotion_type", "=", $promotion_type];
            }
        }
        if (!empty($start_time) && !empty($end_time)) {
            $condition[] = ["create_time", "between", [date_to_time($start_time), date_to_time($end_time)]];
        }
        if ($search_text != "") {
            $condition[] = [$order_label, 'like', "%$search_text%"];
        }
        $order_common_model = new OrderCommonModel();

        $order_export_model = new OrderExport();
        if ($this->user_info['group_id'] == 5) {
            $field = $order_export_model->offer_order_field;
        } else {
            $field = $order_export_model->need_order_field;
        }

        //接收需要展示的字段
        $input_field = input('field', array_keys($field));
        $order = $order_common_model->getOrderList($condition, $input_field, 'order_id desc');
        $order['data']['member_address'] = $order['data']['full_address'].$order['data']['address'];
        $header_arr = array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ'
        );

        //处理数据
        if (!empty($order['data'])) {
            $order_list = $order_export_model->handleData($order['data'], $input_field);
        }else{
            $order_list = [];
        }

        $count = count($input_field);
        // 实例化excel
        $phpExcel = new \PHPExcel();

        $phpExcel->getProperties()->setTitle("订单信息-订单维度");
        $phpExcel->getProperties()->setSubject("订单信息-订单维度");
        //单独添加列名称
        $phpExcel->setActiveSheetIndex(0);


        for ($i = 0; $i < $count; $i++) {
            $phpExcel->getActiveSheet()->setCellValue($header_arr[$i] . '1', $field[$input_field[$i]]);
        }

        if (!empty($order_list)) {
            foreach ($order_list as $k => $v) {
                $start = $k + 2;
                for ($i = 0; $i < $count; $i++) {
                    if (strpos($input_field[$i], ' as ') !== false) {
                        $the_field_arr = explode(' as ', $input_field[$i]);
                        $value = is_numeric($v[$the_field_arr[1]]) ? round($v[$the_field_arr[1]], 2) : $v[$the_field_arr[1]] . "\t";
                    } else {
                        $value = $v[$input_field[$i]] . "\t";
                    }
                    $phpExcel->getActiveSheet()->setCellValue($header_arr[$i] . $start, $value);
                }
            }
        }

        // 重命名工作sheet
        $phpExcel->getActiveSheet()->setTitle('订单信息');
        // 设置第一个sheet为工作的sheet
        $phpExcel->setActiveSheetIndex(0);
        // 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
        $objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
        $file = date('Y年m月d日-订单信息', time()) . '.xlsx';
        $objWriter->save($file);

        header("Content-type:application/octet-stream");

        $filename = basename($file);
        header("Content-Disposition:attachment;filename = " . $filename);
        header("Accept-ranges:bytes");
        header("Accept-length:" . filesize($file));
        readfile($file);
        unlink($file);
        exit;

    }

    /**
     * 订单导出（已订单商品为主）
     */
    public function exportOrderGoods()
    {
        $order_status = input("order_status", "");//订单状态
        $order_name = input("order_name", '');
        $pay_type = input("pay_type", '');
        $order_from = input("order_from", '');
        $start_time = input("start_time", '');
        $end_time = input("end_time", '');
        $order_label = input("order_label",'');
        $search_text = input("search", '');
        $promotion_type = input("promotion_type", '');
        $order_type = input("order_type", 'all');

        $condition[] = ["o.site_id", "=", $this->site_id];
        if($order_type != 'all'){
            $condition[] = ["o.order_type", "=", $order_type];
        }
        //订单状态
        if ($order_status != "") {
            $condition[] = ["o.order_status", "=", $order_status];
        }
        //订单内容 模糊查询
        if ($order_name != "") {
            $condition[] = ["o.order_name", 'like', "%$order_name%"];
        }
        //订单来源
        if ($order_from != "") {
            $condition[] = ["o.order_from", "=", $order_from];
        }
        //订单支付
        if ($pay_type != "") {
            $condition[] = ["o.pay_type", "=", $pay_type];
        }
        $condition[] = ["o.is_delete", "=", 0];
        //营销类型
        if ($promotion_type != "") {
            if ($promotion_type == 'empty') {
                $condition[] = ["o.promotion_type", "=", ''];
            } else {
                $condition[] = ["o.promotion_type", "=", $promotion_type];
            }
        }
        if (!empty($start_time) && !empty($end_time)) {
            $condition[] = ["o.create_time", "between", [date_to_time($start_time), date_to_time($end_time)]];
        }
        if ($search_text != "") {
            $condition[] = ['o.' . $order_label, 'like', "%$search_text%"];
        }
        $order_common_model = new OrderCommonModel();
        $order_export_model = new OrderExport();
        if ($this->user_info['group_id'] == 5) {
            $field = $order_export_model->offer_order_field;
            $condition[] = ["og.offer_member", "=", $this->uid];
        } else {
            $field = $order_export_model->need_order_field;
        }

//        $field = array_merge($order_export_model->order_goods_field,$order_export_model->order_field);
        //接收需要展示的字段
        $input_field = input('field', array_keys($field));
        $order = $order_common_model->getOrderGoodsDetailList($condition);
        foreach ($order['data'] as $k => $v) {
            $order['data'][$k]['member_address'] = $v['full_address'].$v['address'];
            $order['data'][$k]['offer_member_name'] = Db::name('user')->where('uid', $v['offer_member'])->value('offer_name') ?? '';
            $leader_id = Db::name('member')->where('member_id', $v['member_id'])->value('leader_member');
            $order['data'][$k]['leader_name'] = Db::name('member')->where('member_id', $leader_id)->value('realname');
            $order['data'][$k]['modify_price'] = round($v['real_goods_money'] / $v['num'], 2);
        }
        $header_arr = array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ'
        );
        //处理数据
        $order_list = [];
        if (!empty($order['data'])) {
            $order_list = $order_export_model->handleData($order['data'], $input_field);
        }

        $count = count($input_field);
        // 实例化excel
        $phpExcel = new \PHPExcel();

        $phpExcel->getProperties()->setTitle("订单信息");
        $phpExcel->getProperties()->setSubject("订单信息");
        //单独添加列名称
        $phpExcel->setActiveSheetIndex(0);


        for ($i = 0; $i < $count; $i++) {
            $phpExcel->getActiveSheet()->setCellValue($header_arr[$i] . '1', $field[$input_field[$i]]);
        }

        if (!empty($order_list)) {
            foreach ($order_list as $k => $v) {
                $start = $k + 2;
                for ($i = 0; $i < $count; $i++) {

                    $value = $v[$input_field[$i]] . "\t";
                    $phpExcel->getActiveSheet()->setCellValue($header_arr[$i] . $start, $value);
                }
            }
        }

        // 重命名工作sheet
        $phpExcel->getActiveSheet()->setTitle('订单信息-商品维度');
        // 设置第一个sheet为工作的sheet
        $phpExcel->setActiveSheetIndex(0);
        // 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
        $objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
        $file = date('Y年m月d日-订单信息', time()) . '.xlsx';
        $objWriter->save($file);

        header("Content-type:application/octet-stream");

        $filename = basename($file);
        header("Content-Disposition:attachment;filename = " . $filename);
        header("Accept-ranges:bytes");
        header("Accept-length:" . filesize($file));
        readfile($file);
        unlink($file);
        exit;

    }

    /**
     * 订单导出（维权订单）
     */
    public function exportRefundOrder()
    {
        $refund_status = input("refund_status", "");//退款状态
        $sku_name = input("sku_name", '');//商品名称
        $refund_type = input("refund_type", '');//退款方式
        $start_time = input("start_time", '');//开始时间
        $end_time = input("end_time", '');//结束时间
        $order_no = input("order_no", '');//订单编号
        $delivery_status = input("delivery_status", '');//物流状态
        $refund_no = input("refund_no", '');//退款编号

        $delivery_no = input("delivery_no", '');//物流编号
        $refund_delivery_no = input("refund_delivery_no", '');//退款物流编号

        $order_common_model = new OrderCommonModel();

        $condition[] = ['og.site_id', '=', $this->site_id];
        //退款状态
        if ($refund_status != "") {
            $condition[] = ["og.refund_status", "=", $refund_status];
        } else {
            $condition[] = ["og.refund_status", "<>", 0];
        }
        //物流状态
        if ($delivery_status != "") {
            $condition[] = ["og.delivery_status", "=", $delivery_status];
        }
        //商品名称
        if ($sku_name != "") {
            $condition[] = ["og.sku_name", "like", "%$sku_name%"];
        }
        //退款方式
        if ($refund_type != "") {
            $condition[] = ["og.refund_type", "=", $refund_type];
        }
        //退款编号
        if ($refund_no != "") {
            $condition[] = ["og.refund_no", "like", "%$refund_no%"];
        }
        //订单编号
        if ($order_no != "") {
            $condition[] = ["og.order_no", "like", "%$order_no%"];
        }
        //物流编号
        if ($delivery_no != "") {
            $condition[] = ["og.delivery_no", "like", "%$delivery_no%"];
        }
        //退款物流编号
        if ($refund_delivery_no != "") {
            $condition[] = ["og.refund_delivery_no", "like", "%$refund_delivery_no%"];
        }

        if (!empty($start_time) && empty($end_time)) {
            $condition[] = ["og.refund_action_time", ">=", date_to_time($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $condition[] = ["og.refund_action_time", "<=", date_to_time($end_time)];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $condition[] = ['og.refund_action_time', 'between', [date_to_time($start_time), date_to_time($end_time)]];
        }

        $order_export_model = new OrderExport();
        $field = array_merge($order_export_model->order_goods_field,$order_export_model->order_field);
        //接收需要展示的字段
        $input_field = input('field', array_keys($field));
        $order = $order_common_model->getOrderGoodsDetailList($condition);
        $header_arr = array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ'
        );

        //处理数据
        $order_list = [];
        if (!empty($order['data'])) {
            $order_list = $order_export_model->handleData($order['data'], $input_field);
        }

        $count = count($input_field);
        // 实例化excel
        $phpExcel = new \PHPExcel();

        $phpExcel->getProperties()->setTitle("退款维权订单");
        $phpExcel->getProperties()->setSubject("退款维权订单");
        //单独添加列名称
        $phpExcel->setActiveSheetIndex(0);


        for ($i = 0; $i < $count; $i++) {
            $phpExcel->getActiveSheet()->setCellValue($header_arr[$i] . '1', $field[$input_field[$i]]);
        }

        if (!empty($order_list)) {
            foreach ($order_list as $k => $v) {
                $start = $k + 2;
                for ($i = 0; $i < $count; $i++) {

                    $value = $v[$input_field[$i]] . "\t";
                    $phpExcel->getActiveSheet()->setCellValue($header_arr[$i] . $start, $value);
                }
            }
        }

        // 重命名工作sheet
        $phpExcel->getActiveSheet()->setTitle('退款维权订单');
        // 设置第一个sheet为工作的sheet
        $phpExcel->setActiveSheetIndex(0);
        // 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
        $objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
        $file = date('Y年m月d日-退款维权订单', time()) . '.xlsx';
        $objWriter->save($file);

        header("Content-type:application/octet-stream");

        $filename = basename($file);
        header("Content-Disposition:attachment;filename = " . $filename);
        header("Accept-ranges:bytes");
        header("Accept-length:" . filesize($file));
        readfile($file);
        unlink($file);
        exit;
    }

    /**
     * 导出字段
     * @return array
     */
    public function getPrintingField()
    {
        $model = new OrderExport();
        $data = [
            'order_field' => $model->order_field,
            'order_goods_field' => $model->order_goods_field
        ];

        return success('1', '', $data);
    }

    public function printOrder()
    {
        $order_id = input('order_id', 0);
        $order_common_model = new OrderCommonModel();
        $order_detail_result = $order_common_model->getOrderDetail($order_id);
        $order_detail = $order_detail_result["data"];
        $order_detail['offer_name'] = Db::name('user')->where('uid', $order_detail['order_goods'][0]['offer_member'])->value('offer_name') ?? '';
        $this->assign("order_detail", $order_detail);
        return $this->fetch('order/print_order');
    }

    public function printOrder2()
    {
        $order_id = input('order_id', 0);
        $order_common_model = new OrderCommonModel();
        $order_detail_result = $order_common_model->getOrderDetail($order_id);
        $order_detail = $order_detail_result["data"];
        $order_detail['offer_name'] = Db::name('user')->where('uid', $this->uid)->value('offer_name') ?? '';
        $this->assign("order_detail", $order_detail);
        return $this->fetch('order/print_order2');
    }

    /**
     * 交易记录
     */
    public function tradelist()
    {
        $order_common_model = new OrderCommonModel();
        if (request()->isAjax()) {
            $page = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);
            $member_id = input('member_id', 0);//会员id
            $search_text = input('search_text', 0);//h关键字查询
            $condition = array();
            if ($member_id > 0) {
                $condition[] = ["member_id", "=", $member_id];
            }
            if (!empty($search_text)) {
                $condition[] = ['order_no|order_name', 'like', '%' . $search_text . '%'];
            }

            return $order_common_model->getTradePageList($condition, $page, $page_size, "create_time desc");

        }
    }

    /**
     * 订单关闭
     * @return mixed
     */
    public function delete()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $order_common_model = new OrderCommonModel();
            $result = $order_common_model->orderDelete($order_id);
            return $result;
        }
    }

    /**
     * 线下支付
     * @return array
     */
    public function offlinePay()
    {
        if (request()->isAjax()) {
            $order_id = input("order_id", 0);
            $order_common_model = new OrderCommonModel();
            $result = $order_common_model->orderOfflinePay($order_id);
            return $result;
        }
    }

    /**
     * 订单列表（发票）
     */
    public function invoiceOrderList()
    {
        if (request()->isAjax()) {
            $page_index = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);
            $condition = [
                ["site_id", "=", $this->site_id],
                ['is_delete', '=', 0],
                ['is_invoice', '=', 1]
            ];

            //订单编号
            $order_no = input('order_no', '');
            if ($order_no) {
                $condition[] = ["order_no", "like", "%" . $order_no . "%"];
            }
            //订单状态
            $order_status = input('order_status', '');
            if ($order_status != "") {
                $condition[] = ["order_status", "=", $order_status];
            }
            $order_type = input("order_type", 'all');//营销类型
            $start_time = input('start_time', '');
            $end_time = input('end_time', '');


            //订单类型
            if ($order_type != 'all') {
                $condition[] = ["order_type", "=", $order_type];
            }

            if (!empty($start_time) && empty($end_time)) {
                $condition[] = ["create_time", ">=", date_to_time($start_time)];
            } elseif (empty($start_time) && !empty($end_time)) {
                $condition[] = ["create_time", "<=", date_to_time($end_time)];
            } elseif (!empty($start_time) && !empty($end_time)) {
                $condition[] = ['create_time', 'between', [date_to_time($start_time), date_to_time($end_time)]];
            }

            $order_common_model = new OrderCommonModel();
            $list = $order_common_model->getOrderPageList($condition, $page_index, $page_size, "create_time desc");
            return $list;
        } else {
            $order_model = new OrderModel();
            $order_status_list = $order_model->order_status;
            $this->assign("order_status_list", $order_status_list);//订单状态
            $order_common_model = new OrderCommonModel();
            $order_type_list = $order_common_model->getOrderTypeStatusList();
            $this->assign("order_type_list", $order_type_list);

            return $this->fetch('order/invoice_list');
        }
    }

    /**
     * 发票导出
     */
    public function exportInvoice()
    {
        $page_index = input('page', 1);
        $page_size = 0;
        $condition = [
            ["site_id", "=", $this->site_id],
            ['is_delete', '=', 0],
            ['is_invoice', '=', 1]
        ];

        //订单编号
        $order_no = input('order_no', '');
        if ($order_no) {
            $condition[] = ["order_no", "like", "%" . $order_no . "%"];
        }
        //订单状态
        $order_status = input('order_status', '');
        if ($order_status != "") {
            $condition[] = ["order_status", "=", $order_status];
        }
        $order_type = input("order_type", 'all');//营销类型
        $start_time = input('start_time', '');
        $end_time = input('end_time', '');


        //订单类型
        if ($order_type != 'all') {
            $condition[] = ["order_type", "=", $order_type];
        }

        if (!empty($start_time) && empty($end_time)) {
            $condition[] = ["create_time", ">=", date_to_time($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $condition[] = ["create_time", "<=", date_to_time($end_time)];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $condition[] = ['create_time', 'between', [date_to_time($start_time), date_to_time($end_time)]];
        }

        $order_common_model = new OrderCommonModel();
        $list_result = $order_common_model->getOrderPageList($condition, $page_index, $page_size, "create_time desc");
        $list = $list_result['data']['list'];

        // 实例化excel
        $phpExcel = new \PHPExcel();

        $phpExcel->getProperties()->setTitle("退款维权订单");
        $phpExcel->getProperties()->setSubject("退款维权订单");
        //单独添加列名称
        $phpExcel->setActiveSheetIndex(0);

        $phpExcel->getActiveSheet()->setCellValue("A1", '订单编号');
        $phpExcel->getActiveSheet()->setCellValue("B1", '订单总额（元）');
        $phpExcel->getActiveSheet()->setCellValue("C1", '发票税费');
        $phpExcel->getActiveSheet()->setCellValue("D1", '发票邮寄费用');
        $phpExcel->getActiveSheet()->setCellValue("E1", '发票类型');
        $phpExcel->getActiveSheet()->setCellValue("F1", '发票抬头');
        $phpExcel->getActiveSheet()->setCellValue("G1", '抬头类型');
        $phpExcel->getActiveSheet()->setCellValue("H1", '纳税人识别号');
        $phpExcel->getActiveSheet()->setCellValue("I1", '发票内容');
        $phpExcel->getActiveSheet()->setCellValue("J1", '发票税率（%）');
        $phpExcel->getActiveSheet()->setCellValue("K1", '订单状态');
        $phpExcel->getActiveSheet()->setCellValue("L1", '下单时间');

        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $start = $k + 2;
                $phpExcel->getActiveSheet()->setCellValue('A'. $start, $v['order_no']."\t");
                $phpExcel->getActiveSheet()->setCellValue('B'. $start, $v['order_money']."\t");
                $phpExcel->getActiveSheet()->setCellValue('C'. $start, $v['invoice_money']."\t");
                $phpExcel->getActiveSheet()->setCellValue('D'. $start, $v['invoice_delivery_money']."\t");

                $invoice_name = '';
                if($v['invoice_type'] == 1){
                    $invoice_name = '纸质';
                }else{
                    $invoice_name = '电子';
                }
                if($v['is_tax_invoice'] == 1){
                    $invoice_name .= '专用发票';
                }else{
                    $invoice_name .= '普通发票';
                }
                $phpExcel->getActiveSheet()->setCellValue('E'. $start, $invoice_name."\t");
                $phpExcel->getActiveSheet()->setCellValue('F'. $start, $v['invoice_title']."\t");
                $invoice_title_type = $v['invoice_title_type'] == 1 ? '个人' : '企业';
                $phpExcel->getActiveSheet()->setCellValue('G'. $start, $invoice_title_type ."\t");
                $phpExcel->getActiveSheet()->setCellValue('H'. $start, $v['taxpayer_number']."\t");
                $phpExcel->getActiveSheet()->setCellValue('I'. $start, $v['invoice_title_type']."\t");
                $phpExcel->getActiveSheet()->setCellValue('J'. $start, $v['invoice_rate']."%\t");
                $phpExcel->getActiveSheet()->setCellValue('K'. $start, $v['order_status_name']."\t");
                $phpExcel->getActiveSheet()->setCellValue('L'. $start, time_to_date($v['create_time'])."\t");
            }
        }

        // 重命名工作sheet
        $phpExcel->getActiveSheet()->setTitle('发票列表');
        // 设置第一个sheet为工作的sheet
        $phpExcel->setActiveSheetIndex(0);
        // 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
        $objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
        $file = date('Y年m月d日-发票列表', time()) . '.xlsx';
        $objWriter->save($file);

        header("Content-type:application/octet-stream");

        $filename = basename($file);
        header("Content-Disposition:attachment;filename = " . $filename);
        header("Accept-ranges:bytes");
        header("Accept-length:" . filesize($file));
        readfile($file);
        unlink($file);
        exit;
    }

    /**
     * 供应商选择
     */
    public function getOrderOffer()
    {
        $order_goods_id = input('order_goods_id', 0);
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();

        // 用户默认收货地址
        $user_default_area = getMemberArea($order_goods['member_id']);
        $data = [];
        if (!empty($user_default_area)) {
            $data = getOfferByMember($order_goods['sku_id'], $user_default_area);
        }

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $v['order_goods_id'] = $order_goods_id;
                // 默认无
                $v['province_name'] = $v['city_name'] = $v['district_name'] = '无';
                if ($v['province_id']) {
                    $v['province_name'] = Db::name('area')->where('id', $v['province_id'])->value('name');
                }
                if ($v['city_id']) {
                    $v['city_name'] = Db::name('area')->where('id', $v['city_id'])->value('name');
                }
                if ($v['district_id']) {
                    $v['district_name'] = Db::name('area')->where('id', $v['district_id'])->value('name');
                }
                $data[$k] = $v;
            }
        }
        $result = [
            'code'  =>  0,
            'msg'   =>  '',
            'data'  =>  [
                'list'      =>  $data,
            ],
        ];
        return json($result);
    }

    /**
     * 供应商选择，商品列表页面
     */
    public function getOrderOffer_goods()
    {
        $goods_id = input('goods_id', 0);
        $list = Db::view('offer', '*')
                ->view('goods_sku','sku_name','offer.goods_id=goods_sku.goods_id')
                ->view('user', 'offer_name,offer_person,offer_mobile', 'offer.offer_member=user.uid')
                ->where('offer.goods_id', $goods_id)
                ->order(['offer.offer_member', 'offer.price'], 'asc')
                ->select()
                ->toArray();
        foreach ($list as $k => $v) {
            if ($v['province_id']) {
                $v['province_name'] = Db::name('area')->where('id', $v['province_id'])->value('name') ?? '无';
            }
            if ($v['city_id']) {
                $v['city_name'] = Db::name('area')->where('id', $v['city_id'])->value('name') ?? '无';
            }
            if ($v['district_id']) {
                $v['district_name'] = Db::name('area')->where('id', $v['district_id'])->value('name') ?? '无';
            }
            if (empty($v['price'])) {
                $v['price'] = '无';
            }
            if (empty($v['stock'])) {
                $v['stock'] = '无';
            }
            $list[$k] = $v;
        }
        $result = [
            'code'  =>  0,
            'msg'   =>  '',
            'data'  =>  [
                'list'      =>  $list,
            ],
        ];
        return json($result);
    }

    /**
     * 选择供应商
     */
    public function select_offer()
    {
        $offer_id = input('offer_id', 0);
        $order_goods_id = input('order_goods_id', 0);
        $order_common_model = new OrderCommonModel();
        return $order_common_model->offer_select($offer_id, $order_goods_id);
    }

    /**
     * 下单审核
     */
    public function review()
    {
        $order_goods_id = input('order_goods_id', 0);
        $review = input('review', 1);
        if ($this->user_info['group_id'] <> 1){
            return json([
                'code'  =>  1,
                'msg'   =>  '只有管理员组的用户才有权限审核',
            ]);
        }
        $order_goods_data = Db::name('order_goods')->find($order_goods_id);
        if ($order_goods_data['review']){
            return json([
                'code'  =>  1,
                'msg'   =>  '此订单已审核，请勿重复操作',
            ]);
        }
        try {
            //通过
            if (!empty($review)){
                //标记
                Db::name('order_goods')->where('order_goods_id', $order_goods_id)->update([
                    'review' => 1
                ]);

                //管理员审核通过，提醒供应商发货
                $mobile = Db::name('user')->where('uid', $order_goods_data['offer_member'])->value('offer_mobile');
                if (!empty($mobile)){
                    (new Message())->send_sms($mobile,'1132842', [$order_goods_data['order_no']]);
                }
            }else{
                //拒绝
                //相关供应商库存恢复
                Db::name('offer')->where([
                    'sku_id'        => $order_goods_data['sku_id'],
                    'offer_member'  => $order_goods_data['offer_member']
                ])->update([
                    'stock' =>  Db::raw('stock+'.$order_goods_data['num']),
                ]);
                //初始化订单的供应商信息
                Db::name('order_goods')->where('order_goods_id', $order_goods_id)->update([
                    'offer'        => 0,
                    'offer_id'     => 0,
                    'offer_member' => 0,
                    'offer_price'  => 0,
                ]);
            }
            $code = 0;
            $msg = !empty($review) ? '下单已通过，请等待供应商发货' : '下单已拒绝，请重新下单';
        }catch (\Exception $e){
            $code = 1;
            $msg = $e->getMessage();
        }
        $result = [
            'code'  =>  $code,
            'msg'   =>  $msg,
        ];
        return json($result);
    }

    /**
     * 呼叫货拉拉
     */
    public function tel_hll()
    {
        $order_goods_id = input('order_goods_id');
        $this->assign([
            'order_goods_id'    =>      $order_goods_id,
        ]);
        return $this->fetch('order/offer_tel_hll');
    }

    /**
     * 添加区域报价
     */
    public function offer_set_location()
    {
        if (empty($this->uid)){
            return $this->error('','对不起，您不是供应商');
        }
        $sku_id = intval(input('sku_id', 0));
        $province_id = intval(input('province_id', 0));
        $city_id = intval(input('city_id', 0));
        $district_id = intval(input('district_id', 0));
        $price = floatval(input('price', 0));
        $stock = intval(input('stock', 0));
        $goods_model = new GoodsModel();
        $result = $goods_model->goods_location($sku_id, $province_id, $city_id, $district_id, $price, $stock, $this->uid);
        return $result;
    }

    // 获取区域报价
    public function offer_get_location()
    {
        if (empty($this->uid)){
            return $this->error('','对不起，您不是供应商');
        }
        $sku_id = intval(input('sku_id', 0));
        $goods_model = new GoodsModel();
        $result = $goods_model->offer_get_location($sku_id, $this->uid);
        return $result;
    }

    // 删除区域报价
    public function offer_delete_location()
    {
        if (empty($this->uid)){
            return $this->error('','对不起，您不是供应商');
        }
        $id = intval(input('id', 0));
        $goods_model = new GoodsModel();
        $result = $goods_model->offer_delete_location($id, $this->uid);
        return $result;
    }
}